#pragma once

#include "parameter.h"

int show_bt_bmp(char *bmp_name, int lcd_fd,int excursion_x,int excursion_y) // 显示图片.左上角
{
    // 2.打开图片文件
    int bmp_fd = openfd(bmp_name, O_RDWR);

    // 3.申请映射内存
    int *lcd_p = mmap(NULL, 800 * 480 * 4, PROT_READ | PROT_WRITE, MAP_SHARED, lcd_fd, 0);

    //偏移
    int *excursion_p = lcd_p + excursion_x + excursion_y * 800;

    int wide, height; // 获取图片的宽高
    lseek(bmp_fd, 18, SEEK_SET);
    read(bmp_fd, &wide, 4);
    lseek(bmp_fd, 22, SEEK_SET);
    read(bmp_fd, &height, 4);
    // printf("W:%d,H:%d\n", wide, height);

    int num = 0; // 每一行补齐的字节数
    if ((wide * 3) % 4 == 0)
    {
        num = 0;
    }
    else
    {
        num = 4 - (wide * 3 % 4);
    }
    // printf("num=%d\n", num);

    // 5.读图片文件wide*height*3字节，这些是剩下纯RGB数据
    int max = wide * height * 3 + num * height;
    char buf_1[max];
    bzero(buf_1, sizeof(buf_1));
    lseek(bmp_fd, 54, SEEK_SET); // 跳过格式头的54个字节
    int ret = read(bmp_fd, buf_1, sizeof(buf_1));

    // 6.将读取出来的RGB数据转化成ARGB数据
    // printf("ret=%d\n", ret);
    int buf_2[wide * height]; // 存储处理完毕的像素点
    bzero(buf_2, sizeof(buf_2));
    int n = 0;
    for (int y1 = 0; y1 < height; y1++) // 6、24bits 转 32bits控制变量
    {
        for (int x1 = 0; x1 < wide; x1++, n += 3)
        {
            buf_2[x1 + wide * (y1)] = buf_1[n] << 0 | buf_1[(n) + 1] << 8 | buf_1[(n) + 2] << 16;
        }
        n += num; // 在上面内层for循环中，通过n遍历完成一行的所有像素点的rgb对应数据之后，跳过num个字节的补齐数据
    }

    // 7.将ARGB数据写入开发板
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < wide; x++)
        {
            if((x - 35) * (x - 35) + (y - 35) * (y - 35) <= 35 * 35)
                *(lcd_p + (800 * ((height - 1 + excursion_y) - y)) + x + excursion_x)  = buf_2[x + y * wide];
        }
    }

    // 8.关闭图片文件
    close(bmp_fd);

    // 9.解除映射内存
    munmap(lcd_p, 800 * 480 * 4);
}